package saas.consumer.service.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpRequest;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import saas.consumer.service.biz.BizService;
import saas.consumer.service.biz.TenantConversionRelation;
import saas.consumer.service.remote.BzFeignClient;
import saas.consumer.service.remote.OmsFeignClient;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @title: MainController
 * @description: 主控制器
 * @author: guan.xin
 * @create: 2021-11-12 15:33
 * @since: JDK8
 */

@RequestMapping("/main")
@RestController
@Slf4j
public class MainController {

    @Resource
    private OmsFeignClient omsFeignClient;

    @Resource
    private BzFeignClient bzFeignClient;

    @Resource
    private BizService bizService;

    @Resource
    ApplicationContext applicationContext;

    @PostMapping(value = "/upload")
    public void upload() throws FileNotFoundException {
        File file = new File("/Users/guan.xin/Gitee/Python/pythonProject/parquet_files/so_order.parquet");
        if (file.exists()) {
            //String ossUrl = fileUploadUtils.uploadInputStream(new FileInputStream(file), "par", "ecs-task-engine/task-engine");
            //System.out.println(ossUrl);
        } else {
            System.out.println("文件不存在");
        }

    }


    @PostMapping(value = "/get")
    public String getHello(HttpServletRequest request) throws IOException {
        Map<String, TenantConversionRelation> map = bizService.getMap();

        String s = new String(StreamUtils.copyToByteArray(request.getInputStream()));

        if (map.containsKey(s)) {
            log.info("成功");
        } else {
            log.error("失败");
        }


//        log.info("访问测试日志：{}", "hello world!");
//        MessageCommond mc = new MessageCommond();
//        mc.setTopic("BIZ_SERVICE_CONSUMER");
//        mc.setMsgBody(empCode);
//        mc.setMsgId("1");
//        BizService bizService = BizService.newInstance();
//        bizService.consume(mc);
//
//        BizService bean = applicationContext.getBean(BizService.class);
//        Class<? extends BizService> aClass = bean.getClass();
//        Method method = aClass.getMethod("consume", MessageCommond.class);
//        method.invoke(aClass.newInstance(), mc);
//
//        log.info(TenantContext.getCurrentSaaSTenantCode());
//        log.info(ServiceContextHolder.getRemoteSaaSTenantFlagContext());
//        return TenantContext.getCurrentSaaSTenantCode();
        return "";
    }

    @PostMapping(value = "/post")
    public String postHello(@RequestParam String empCode) {
//        log.info("访问测试日志：{}, {}", "hello world!", empCode);
//        log.info("getRemoteSaaSTenantFlagContext, {}", ServiceContextHolder.getRemoteSaaSTenantFlagContext());
//        omsFeignClient.remote(empCode, "JD_PUMA");
//        return TenantContext.getCurrentSaaSTenantCode();
        return "";
    }

    @PostMapping(value = "/client1")
    public String client1Hello(@RequestParam String empCode) throws URISyntaxException, IOException {
        // 消费
//        List<ConsumeMessageHookCallback> list1 = hookLocator.getConsumeMessageHookList();
//
//        list1.forEach(e -> {
//            ConsumeMessageHook hookObject = e.getHookObject();
//            log.info(hookObject.hookName());
//            hookObject.consumeMessageBefore(null);
//            hookObject.consumeMessageAfter(null);
//        });
//
//        // 生产
//        List<SendMessageHookCallback> list2 = hookLocator.getSendMessageHookList();
//
//        list2.forEach(e -> {
//            SendMessageHook hookObject = e.getHookObject();
//            log.info(hookObject.hookName());
//            hookObject.sendMessageBefore(null);
//            hookObject.sendMessageAfter(null);
//        });

//        log.info("访问测试日志：{}", "hello world!");
//        log.info("getRemoteSaaSTenantFlagContext, {}", ServiceContextHolder.getRemoteSaaSTenantFlagContext());
//        // 创建Httpclient对象
//        CloseableHttpClient httpclient = HttpClients.custom()
//                .addInterceptorFirst(new HttpclientOutboundSaasTenantMappingInterceptor()).build();
//        // 创建http POST请求
//        HttpPost httpPost = new HttpPost("http://localhost:9091/main/remote");
//        // 设置2个post参数，一个是scope、一个是q
//        List<NameValuePair> parameters = new ArrayList<>(0);
//        parameters.add(new BasicNameValuePair("saasStoreCode", "JD_PUMA"));
//        parameters.add(new BasicNameValuePair("empCode", empCode));
//        // 构造一个form表单式的实体
//        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
//        // 将请求实体设置到httpPost对象中
//        httpPost.setEntity(formEntity);
//        //伪装浏览器
//        httpPost.setHeader("User-Agent",
//                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
//        CloseableHttpResponse response = null;
//        try {
//            // 执行请求
//            response = httpclient.execute(httpPost);
//            // 判断返回状态是否为200
//            if (response.getStatusLine().getStatusCode() == 200) {
//                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//                //内容写入文件
//                log.info("内容：" + content);
//            }
//        } finally {
//            if (response != null) {
//                response.close();
//            }
//            httpclient.close();
//        }
//
//        omsFeignClient.remote(empCode, "JD_PUMA");
//        return TenantContext.getCurrentSaaSTenantCode();
        return null;
    }

    @PostMapping(value = "/client2")
    public String client2Hello(@RequestParam String empCode) throws URISyntaxException, IOException {
//        log.info("访问测试日志：{}", "hello world!");
//        log.info("getRemoteSaaSTenantFlagContext, {}", ServiceContextHolder.getRemoteSaaSTenantFlagContext());
//        // 创建Httpclient对象
//        CloseableHttpClient httpclient = HttpClients.custom()
//                .addInterceptorFirst(new HttpclientOutboundSaasTenantMappingInterceptor()).build();
//        // 定义请求的参数
//        URI uri = new URIBuilder("http://localhost:9091/main/remote")
//                .setParameter("saasStoreCode", "JD_PUMA")
//                .setParameter("empCode", empCode)
//                .build();
//        // 创建http GET请求
//        HttpGet httpGet = new HttpGet(uri);
//        //response 对象
//        CloseableHttpResponse response = null;
//        try {
//            // 执行http get请求
//            response = httpclient.execute(httpGet);
//            // 判断返回状态是否为200
//            if (response.getStatusLine().getStatusCode() == 200) {
//                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//                log.info("内容：" + content);
//            }
//        } finally {
//            if (response != null) {
//                response.close();
//            }
//            httpclient.close();
//        }
//        return TenantContext.getCurrentSaaSTenantCode();
        return null;
    }

    @GetMapping("/aop")
    public void aop() {
        String s = bizService.testAop();
        System.out.println(s);

        String s2 = bizService.testAop2("hello");
        System.out.println(s2);
    }
}
